package it.mbus.bz;

import it.mbus.component.UserComponent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		
		final ImageView button = (ImageView) findViewById(R.id.btnEntra);
		final EditText us = (EditText) findViewById(R.id.editText1);
		final EditText ps = (EditText) findViewById(R.id.editText2);
		final CheckBox sa = (CheckBox) findViewById(R.id.salva);
		
		button.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				button.setImageResource(R.drawable.entra_norm);
				return false;
			}
		});

		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				button.setImageResource(R.drawable.entra_pres);
				String u = us.getText().toString();
				String p = ps.getText().toString();
				boolean s = sa.isChecked();

				if (u.equals("") || p.equals("")) {
					Toast.makeText(getBaseContext(),
							"Nome Utente o Password ASSENTI",
							Toast.LENGTH_SHORT).show();
				} else {

					if (UserComponent.login(u,p)) {// controlla login
						
						if (s) {// login + salvataggio dati
							UserComponent.salvaDatiUtente(u, p);
							Toast.makeText(getBaseContext(),
									"Login effettuato e dati salvati",
									Toast.LENGTH_SHORT).show();
							Intent localIntent = new Intent();
				            localIntent.setClass(Login.this, Home.class);
				            LogReg.handleToClose.finish(); //questo chiude l' activity logReg
				            Login.this.startActivity(localIntent);
				            finish();
							
						} else {// login SENZA salvataggio dati
							Toast.makeText(getBaseContext(),
									"Login effettuato", Toast.LENGTH_SHORT)
									.show();
							Intent localIntent = new Intent();
				            localIntent.setClass(Login.this, Home.class);
				            LogReg.handleToClose.finish(); //questo chiude l' activity logReg
				            Login.this.startActivity(localIntent);
				            finish();
						}
						// PARTE ACTIVTY HOME + FINISH()
					} else {// psw o usr ERRATI
						Toast.makeText(getBaseContext(),
								"Nome Utente o Password ERRATI",
								Toast.LENGTH_SHORT).show();

						
					}

				}

			}
		});
	}
}
